package com.kobe.algorithm.leetcode.case116;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author ：caopengfei
 * @date ：2021/2/25
 */
public class Solution116 {

    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if(root == null){
            return null;
        }
        queue.offer(root);

        while(!queue.isEmpty()){
            int n = queue.size();
            for (int i = 0; i < n ; i++) {
                Node node = queue.poll();
                //将next指向右侧节点
                if(i < n-1){
                    node.next = queue.peek();
                }
                Node left = node.left;
                Node right = node.right;
                if(left != null){
                    queue.offer(left);
                }
                if(right != null){
                    queue.offer(right);
                }
            }
        }
        return  root;
    }

    public static void main(String[] args) {
        Node node = new Node(1);
        node.left =  new Node(2);
        node.right =  new Node(3);
        node.left.left =  new Node(4);
        node.left.right =  new Node(5);
        node.right.left =  new Node(6);
        node.right.right =  new Node(7);
        Solution116 solution116 = new Solution116();
        solution116.connect(node);
    }

}
